package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Linked;
import cn.edu.seu.herald.informationplatform.bean.league.Message;
import cn.edu.seu.herald.informationplatform.bean.league.ViewMessage;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueInfoDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;
import cn.edu.seu.herald.informationplatform.dao.database.MessageDao;
import cn.edu.seu.herald.informationplatform.dao.database.RecruitDao;
import cn.edu.seu.herald.informationplatform.dao.database.UserDao;

public class RecruitMessagesRequired implements Filter {
	
	private static final String MESSAGES_SIZE_ID = "messagesSize";
	
	private static final String MESSAGES_ID = "messages";
	
	@Override
	public void init(FilterConfig config) throws ServletException {}

	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		int leagueId = getLeagueId(httpRequest);
		
		try {
			MessageDao mdao = MessageDao.getDao();
			Map<Integer, Message> messageMapping =
					mdao.getMessageFromRecruitId(leagueId);
			List<Linked<ViewMessage>> viewMessages =
					parseToViewMessages(messageMapping);
			request.setAttribute(MESSAGES_SIZE_ID, viewMessages.size());
			request.setAttribute(MESSAGES_ID, viewMessages);
		} catch (SQLException e) {
			httpResponse.sendError(404, "resource not found");
			return;
		}
		
		chain.doFilter(request, response);
	}
	
	private int getLeagueId(HttpServletRequest httpRequest) {
		String leagueIdParam = httpRequest.getParameter(
				LeagueSpecified.PARAM_NAME_OF_LEAGUE_ID);
		return Integer.parseInt(leagueIdParam);
	}
	
	private static List<Linked<ViewMessage>> parseToViewMessages(
			Map<Integer, Message> messageMap) {
		if (messageMap == null) {
			return null;
		}
		
		LinkedList<Linked<ViewMessage>> viewMessages =
				new LinkedList<Linked<ViewMessage>>();
		for (Entry<Integer, Message> e: messageMap.entrySet()) {
			int key = e.getKey();
			Message value = e.getValue();
			ViewMessage vm = parseToViewMessage(value);
			
			Linked<ViewMessage> l = new Linked<ViewMessage>();
			l.setEntity(vm);
			l.setLink(new Integer(key).toString());
			viewMessages.add(l);
		}
		return viewMessages;
	}
	
	private static ViewMessage parseToViewMessage(Message message) {
		if (message == null) {
			return null;
		}
		
		String content = message.getContent();
		String userOrLeague = message.getUserOrLeague();
		int id = message.getUserOrLeagueId();
		Timestamp time = message.getTime();
		
		ViewMessage viewMessage = new ViewMessage();
		viewMessage.setContent(content);
		
		Date date = (time == null) ? null : new Date(time.getTime());
		viewMessage.setDate(date);
		
		if ("USER".equalsIgnoreCase(userOrLeague)) {
			viewMessage.setUserId(id);
		}
		if ("LEAGUE".equalsIgnoreCase(userOrLeague)) {
			viewMessage.setLeagueId(id);
		}
		
		String name = "（匿名）";
		try {
			if (userOrLeague != null && userOrLeague.equalsIgnoreCase("user")) {
				UserDao dao = UserDao.getDao();
				name = dao.getUserById(id).getTruename();
			}
			if (userOrLeague != null && userOrLeague.equalsIgnoreCase("league")) {
				LeagueUserDao udao = LeagueUserDao.getDao();
				int infoId = udao.getLeagueUser(id).getLeagueInfoId();
				LeagueInfoDao idao = LeagueInfoDao.getDao();
				name = idao.getLeagueInfo(infoId).getName();
			}
		} catch (SQLException e) {}
		viewMessage.setName(name);
		
		return viewMessage;
	}

}
